<template>
  <div class="container">
    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="never">
      <div class="search-wrapper">
        <el-form :inline="true" :model="queryParams" ref="queryForm" class="demo-form-inline">
          <el-form-item label="项目名称">
            <el-input
              :model-value="selectedProject ? selectedProject.name : ''"
              placeholder="请选择项目"
              readonly
              class="selector-input"
            >
              <template #append>
                <el-button @click="openProjectSelector">选择</el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="设备类别">
            <el-select
              v-model="queryParams.type"
              placeholder="请选择设备类别"
              clearable
              style="width: 220px"
            >
              <el-option
                v-for="item in typeOptions"
                :key="item.dictLabel"
                :label="item.dictLabel"
                :value="item.dictLabel"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="queryParams.activate"
                       placeholder="是否生效"
                       clearable
                       style="width: 110px">
              <el-option label="生效" :value="1" />
              <el-option label="作废" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery" icon="Search">
              查询
            </el-button>
            <el-button @click="resetQuery" icon="RefreshLeft">
              重置
            </el-button>
          </el-form-item>
          <!-- 添加按钮 -->
          <el-form-item>
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon> 新增设备核价
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 数据列表 -->
    <el-card class="list-card" shadow="never">
      <el-table
        v-loading="loading"
        :data="dataList"
        :height="tableHeight"
        element-loading-text="加载中..."
        element-loading-background="rgba(255, 255, 255, 0.7)"
        style="width: 100%"
        stripe
        border
      >
        <el-table-column type="index" width="60" label="序号" align="center" />
        <el-table-column prop="projectName" label="项目名称" min-width="200" align="center" show-overflow-tooltip />
        <el-table-column prop="type" label="设备类别" min-width="120" align="center" show-overflow-tooltip />
        <el-table-column prop="sumPrice" label="总金额(元)" min-width="120" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span class="price-value">{{ formatPrice(scope.row.sumPrice) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="180" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span class="date-value">{{ formatDate(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="270" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleDetail(scope.row.id)">
              查看
            </el-button>
            <el-button type="primary" size="small" @click="handleEdit(scope.row.id)">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row.id)">
              删除
            </el-button>
            <el-switch v-model="scope.row.activate"
                       class="ml-2"
                       inline-prompt
                       style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949;margin-left: 15px"
                       active-text="生效"
                       inactive-text="作废"
                       :active-value="1"
                       :inactive-value="0"
                       @change="activateChange($event === 1,scope.row.id)" />
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.limit"
          :page-sizes="[10, 20, 50, 100]"
          :background="true"
          layout="prev, pager, next, jumper,->,sizes,total"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </el-card>

    <!-- 项目选择器对话框 -->
    <ArchiveSelector
      v-model="projectSelectorVisible"
      title="选择项目"
      :search-fields="projectSearchFields"
      :table-columns="projectTableColumns"
      :fetch-data-api="getProjectList"
      :multiple="false"
      @confirm="handleProjectSelect"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getDevicePricingListApi, deleteDevicePricingApi, updateStatusApi } from '@/api/devicePricing/index'
import type { DevicePricingPlan, DevicePricingQuery } from '@/api/devicePricing/type'
import { Search, Refresh, Plus, Edit, Delete, View } from '@element-plus/icons-vue'
import { getListApi as getDictListApi } from "@/api/sysDictData" 
import { SysDictData } from "@/api/sysDictData/type"
import ArchiveSelector from "@/components/common/ArchiveSelector.vue"
import { getProjectDocumentListApi } from '@/api/project'
import { ProjectDocument, ProjectDocumentListParam } from '@/api/project/type'

// 路由实例
const router = useRouter()

// 遮罩层
const loading = ref(true)
// 总条数
const total = ref(0)
// 核价表格数据
const dataList = ref<DevicePricingPlan[]>([])
// 表格高度自适应
const tableHeight = ref(0)
// 设备类别选项
const typeOptions = ref<SysDictData[]>([])

// 查询参数
const queryParams = reactive<DevicePricingQuery>({
  page: 1,
  limit: 10,
  projectId: undefined,
  type: undefined,
  activate: undefined
})

// 项目选择器相关
const projectSelectorVisible = ref(false)
const selectedProject = ref<ProjectDocument | null>(null)

// 项目状态映射
const statusOptions = [
  { value: 0, label: '进行中' },
  { value: 1, label: '已完成' },
  { value: 2, label: '已暂停' },
  { value: 3, label: '已取消' }
]

// 项目选择器搜索字段配置
const projectSearchFields = [
  { label: '项目名称', prop: 'name', type: 'input' as const },
  { label: '项目编号', prop: 'code', type: 'input' as const },
  { label: '客户名称', prop: 'customer', type: 'input' as const },
  {
    label: '项目状态',
    prop: 'status',
    type: 'select' as const,
    options: statusOptions
  }
]

// 项目选择器表格列配置
const projectTableColumns = [
  { prop: 'name', label: '项目名称', width: 250 },
  { prop: 'code', label: '项目编号', width: 250 },
  { prop: 'customer', label: '客户名称', width: 250 },
  { prop: 'manager', label: '项目经理', width: 200 }
]

// 获取设备类别字典
const getTypeOptions = async () => {
  try {
    const res = await getDictListApi({
      dictType: 'ConveyorType', // 假设使用与输送机相同的类型字典
      dictName: "",
      status: undefined,
      page: 0,
      limit: 100
    })
    if (res && res.data) {
      typeOptions.value = res.data.list || []
    }
  } catch (error) {
    console.error('获取设备类别列表失败:', error)
  }
}

// 获取项目列表数据的API方法
const getProjectList = async (params: any) => {
  try {
    // 构建查询参数
    const queryParams: ProjectDocumentListParam = {
      name: params.name,
      code: params.code,
      customer: params.customer,
      status: params.status,
      page: params.page || 1,
      limit: params.limit || 10
    }

    // 调用项目列表API
    return await getProjectDocumentListApi(queryParams)
  } catch (error) {
    console.error('获取项目列表失败:', error)
    return { data: { list: [], total: 0 } }
  }
}

// 处理项目选择确认
const handleProjectSelect = (project: ProjectDocument) => {
  selectedProject.value = project
  queryParams.projectId = project.id
}

// 打开项目选择器
const openProjectSelector = () => {
  projectSelectorVisible.value = true
}

// 查询设备核价列表
const getList = async () => {
  loading.value = true
  isDataLoaded.value = false // 数据加载开始，设置标志位为false
  try {
    const res = await getDevicePricingListApi(queryParams)
    if (res && res.data) {
      dataList.value = res.data.list || []
      total.value = res.data.total || 0
    }
    // 使用nextTick确保DOM更新完成后再设置标志位
    await nextTick()
    isDataLoaded.value = true // 数据加载完成，设置标志位为true
  } catch (error) {
    console.error('获取数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.page = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  selectedProject.value = null
  queryParams.projectId = undefined
  queryParams.type = undefined
  queryParams.activate = undefined
  queryParams.page = 1
  getList()
}

// 修改设备核价单的状态
const updateStatus = reactive({
  id: undefined as number | undefined,
  activate: undefined as boolean | undefined
})

// 标志位：防止初始化时触发
const isDataLoaded = ref(false)

// 激活 作废
const activateChange = async (val: boolean, id: number) => {
  // 如果数据还没加载完成，不执行更新操作
  if (!isDataLoaded.value) return
  
  updateStatus.id = id
  updateStatus.activate = val
  try {
    await updateStatusApi({ id, activate: val ? 1 : 0 })
    ElMessage.success('操作成功')
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 新增按钮操作
const handleAdd = () => {
  router.push('/compute/devicePricing/form')
}

// 修改按钮操作
const handleEdit = (id: number) => {
  router.push(`/compute/devicePricing/form/${id}`)
}

// 查看按钮操作
const handleDetail = (id: number) => {
  router.push(`/compute/devicePricing/form/${id}?display=true`)
}

// 删除按钮操作
const handleDelete = (id: number) => {
  ElMessageBox.confirm('是否确认删除该设备核价记录？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteDevicePricingApi(id).then(() => {
      getList()
      ElMessage.success('删除成功')
    })
  })
}

// 每页条数改变
const handleSizeChange = (size: number) => {
  queryParams.limit = size
  getList()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  queryParams.page = page
  getList()
}

// 格式化日期
const formatDate = (date: string) => {
  if (!date) return ''
  return new Date(date).toLocaleString()
}

// 格式化金额
const formatPrice = (price: number) => {
  return price ? `¥ ${price.toFixed(2)}` : '¥ 0.00'
}

onMounted(() => {
  getTypeOptions()
  getList()
  
  // 设置表格高度
  nextTick(() => {
    tableHeight.value = window.innerHeight - 260
  })
  
  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    nextTick(() => {
      tableHeight.value = window.innerHeight - 260
    })
  })
})
</script>

<style scoped lang="scss">
.container {
  padding: 20px 20px 0px;

  /*顶部搜索卡片*/
  .search-card {
    margin-bottom: 20px;

    :deep(.el-card__body) {
      padding: 15px 20px;
    }

    /*搜索表单*/
    .search-wrapper {
      .demo-form-inline {
        .el-form-item {
          margin-bottom: 0;
          margin-right: 15px;

          &:last-child {
            margin-right: 0;
          }

          .separator {
            margin: 0 5px;
            color: #909399;
          }
        }

        .el-input,
        .el-select {
          width: 220px;
        }
      }
    }
  }

  /*数据表格卡片*/
  .list-card {
    :deep(.el-card__body) {
      padding: 15px 20px 5px;
    }

    /*表格样式*/
    :deep(.el-table) {
      // 表格内容样式
      .price-value {
        font-weight: 600;
        color: #f56c6c;
      }

      .date-value {
        color: #606266;
      }
    }
  }

  // 分页器
  .pagination {
    margin-top: 15px;
    display: flex;
    justify-content: flex-end;
  }
}

// 选择器样式
.selector-input {
  width: 220px;
  
  :deep(.el-input__wrapper) {
    padding-right: 0;
    transition: all 0.3s;
    
    &:hover {
      box-shadow: 0 0 0 1px #409eff inset;
    }
  }
  
  :deep(.el-input-group__append) {
    padding: 0;
    overflow: hidden;
    
    .el-button {
      border-radius: 0;
      height: 100%;
      margin: 0;
      padding: 0 15px;
      color: #fff;
      background-color: #409eff;
      border-color: #409eff;
      transition: all 0.3s;
      
      &:hover {
        background-color: #66b1ff;
        border-color: #66b1ff;
      }
    }
  }
}

</style> 